package com.yuandian.resolver;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.yuandian.enums.S;
import com.yuandian.exception.SqlTemplateException;
import org.jetbrains.annotations.NotNull;
import org.springframework.util.PropertyPlaceholderHelper;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 说明：$模板替换器
 * @Author zfsn
 * @Date 2023/2/16 17:39
 */
public class DollarResolver implements PropertyPlaceholderHelper.PlaceholderResolver {

	private final Map<String, Object> req;

	public DollarResolver(Map<String, Object> req) {
		this.req = req;
	}

	@Override
	public String resolvePlaceholder(@NotNull String placeholderName) {
		Object value = req.get(placeholderName);
		if (value == null) {
			throw new SqlTemplateException("请求参数不包含sql模板中定义的字段：" + placeholderName);
		}
		if (value instanceof List) {
			List<?> valueList = (List<?>) value;
			if (CollUtil.isEmpty(valueList)) {
				return S.BLANK.s();
			}
			Object val = valueList.get(0);
			if (val instanceof String) {
				return S.LEFT_BRACKET.s() +
						valueList.stream().map(v -> S.SINGLE_QUOTES.s() + v + S.SINGLE_QUOTES.s()).collect(Collectors.joining(S.COMMA.s())) +
						S.RIGHT_BRACKET.s();
			}
			return S.LEFT_BRACKET.s() + StrUtil.join(S.COMMA.s(), valueList) + S.RIGHT_BRACKET.s();
		} else if (value instanceof String) {
			return S.SINGLE_QUOTES.s() + value + S.SINGLE_QUOTES.s();
		}
		return String.valueOf(value);
	}
}
